<template>
  <p-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <p-form layout="inline" @keyup.enter.native="searchQuery">
        <p-row :gutter="24"></p-row>
      </p-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <p-row :gutter="24">
        <p-col :span="19">
          <!-- 工单同步按钮
          <p-button @click="handleTheRepairOrderSynchronous" type="primary">工单同步</p-button>-->
          <!-- 齐套确认 -->
          <p-button @click="()=>{showModal();}" type="primary">齐套确认</p-button>
          <!-- 工单导出 -->
          <!-- <p-button @click="handleAdd" type="primary">工单导出</p-button> -->
        </p-col>
        <p-col :span="5">
          <p-form-item label>
            <p-input-search placeholder v-model="queryParam.ruleNo" width="50px"></p-input-search>
          </p-form-item>
        </p-col>
      </p-row>

      <template v-if="cgButtonList && cgButtonList.length>0" v-for="(item,index) in cgButtonList">
        <p-button
          v-if=" item.optType=='js' && (item.groupTag == null || item.groupTag == '' )"
          :key=" 'cgbtn'+index "
          @click="cgButtonJsHandler(item.buttonCode)"
          type="primary"
          :icon="item.buttonIcon"
        >{{ item.buttonName }}</p-button>
        <p-button
          v-else-if=" item.optType=='action' && (item.groupTag == null || item.groupTag == '' )"
          :key=" 'cgbtn'+index "
          @click="cgButtonActionHandler(item.buttonCode)"
          type="primary"
          :icon="item.buttonIcon"
        >{{ item.buttonName }}</p-button>
      </template>
    </div>
    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
        <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>

        <span style="float:right;">
          <a @click="handleExportXls('工序标签维护')">
            <p-icon type="download" />导出
          </a>
          <p-divider type="vertical" />
          <p-upload
            name="file"
            :showUploadList="false"
            :multiple="false"
            :headers="tokenHeader"
            :action="importExcelUrl"
            @change="handleImportExcel"
          >
            <a>
              <p-icon type="import" />导入
            </a>
          </p-upload>
          <p-divider type="vertical" />
          <a @click="loadData()">
            <p-icon type="sync" />刷新
          </a>
          <p-divider type="vertical" />
          <p-popover title="自定义列" trigger="click" placement="leftBottom" :overlay-style="getWidth">
            <template slot="content">
              <p-checkbox-group
                @change="onColSettingsChange"
                v-model="settingColumns"
                :defaultValue="settingColumns"
              >
                <p-row>
                  <template v-for="(item,index) in defColumns">
                    <template v-if="item.key!='rowIndex'&& item.dataIndex!='action'">
                      <p-col :span="12">
                        <p-checkbox :value="item.dataIndex">{{ item.title }}</p-checkbox>
                      </p-col>
                    </template>
                  </template>
                </p-row>
              </p-checkbox-group>
            </template>
            <a>
              <p-icon type="setting" />自定义列
            </a>
          </p-popover>
        </span>
      </div>

      <p-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{fixed:true,selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        @change="handleTableChange"
      >
        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无此图片</span>
          <img
            v-else
            :src="getImgView(text)"
            height="25px"
            alt="图片不存在"
            style="max-width:80px;font-size: 12px;font-style: italic;"
          />
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无此文件</span>
          <p-button
            v-else
            :ghost="true"
            type="primary"
            icon="download"
            size="small"
            @click="uploadFile(text)"
          >下载</p-button>
        </template>

        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>

          <p-divider type="vertical" />
          <p-dropdown>
            <a class="ant-dropdown-link">
              更多
              <p-icon type="down" />
            </a>
            <p-menu slot="overlay">
              <p-menu-item>
                <p-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a>删除</a>
                </p-popconfirm>
              </p-menu-item>
              <template
                v-if="cgButtonLinkList && cgButtonLinkList.length>0"
                v-for="(btnItem,btnIndex) in cgButtonLinkList"
              >
                <p-menu-item :key=" 'cgbtnLink'+btnIndex " v-if="showLinkButton(btnItem,record)">
                  <a
                    href="javascript:void(0);"
                    @click="cgButtonLinkHandler(record,btnItem.buttonCode,btnItem.optType)"
                  >
                    <p-icon v-if="btnItem.buttonIcon" :type="btnItem.buttonIcon" />
                    {{ btnItem.buttonName }}
                  </a>
                </p-menu-item>
              </template>
            </p-menu>
          </p-dropdown>
        </span>
        <!-- table区域-end -->
      </p-table>
    </div>
    <!-- 产出数量对话 -->
    <div>
      <p-modal v-model="numberVisible" title="产出数量" width="50%">
        <MesBcProcessLabelModal :numberList="numberList" @geiChildData="geiChildData"></MesBcProcessLabelModal>
        <template slot="footer">
          <p-button key="back" @click="handleCancel">取消</p-button>
          <p-button key="submit" type="primary" :loading="loading" @click="handleList">确认</p-button>
        </template>
      </p-modal>
    </div>

    <!-- 齐套确认对话框 -->
    <p-modal v-model="visible" title="齐套确认" on-ok="handleOk">
      <template slot="footer">
        <p-button key="back" @click="handleNotOk">取消</p-button>
        <p-button key="submit" type="primary" :loading="loading" @click="handleOk">确认</p-button>
      </template>
      <p>外协工单号是否齐套？</p>
    </p-modal>
  </p-card>
</template>

<script>
import JDictSelectTag from "@/components/SelectTagMes/JDictSelectTagMes.vue";
import { JeecgListMixin } from "@/mixins/JeecgListMixin";
import { api } from "@/api/manage";
import JSuperQuery from "@/components/jeecg/JSuperQuery.vue";
import { filterObj, timestampToDatetime } from "@/utils/util";
import MesBcProcessLabelModal from "./modules/MesBcProcessLabelModal";
import moment from "moment";

import Vue from "vue";
import {
  initDictOptions,
  filterMultiDictText,
} from "@/components/dict/JDictSelectUtil";
import ButtonExpHandler from "@/components/jeecgbiz/modules/ButtonExpHandler";
import { postAction, getAction, putAction } from "@/api/manage";
import FxCompontensModal from "@/components/jeecgbiz/FxCompontensModal";

//高级查询modal需要参数
const superQueryFieldList = [
  {
    value: "process2No",
    text: "二级工序编码",
    type: "string",
  },
  {
    value: "process2Name",
    text: "二级工序名称",
    type: "string",
  },
  {
    value: "process2Explain",
    text: "二级工序描述",
    type: "String",
  },
  {
    value: "labelTemplateNo",
    text: "标签模板编码",
    type: "string",
  },
  {
    value: "labelTemplateName",
    text: "标签模板名称",
    type: "string",
  },
  {
    value: "status",
    text: "状态",
    type: "select",
    dictCode: "mes_open_close",
  },
  {
    value: "remark",
    text: "备注",
    type: "string",
  },
  {
    value: "createB",
    text: "创建人",
    type: "string",
  },
  {
    value: "createTime",
    text: "创建日期 ",
    type: "Date",
  },
  {
    value: "updateBy",
    text: "更新人",
    type: "string",
  },
  {
    value: "updateTime",
    text: "更新日期",
    type: "Date",
  },
];

export default {
  name: "MesMfOutsourcingWorkList",
  mixins: [JeecgListMixin],
  components: {
    JSuperQuery,
    FxCompontensModal,
    MesBcProcessLabelModal,
    JDictSelectTag,
  },
  data() {
    return {
      //产出数量对话框
      numberVisible: false,
      //控制齐套确认对话框的显示与隐藏
      visible: false,
      //传给子组件的数据
      numberList: [],
      // 子组件传过来的数据
      childData: [],
      fieldList: superQueryFieldList,
      superQueryFlag: false,
      superQueryParams: "",
      description: "工序标签维护管理页面",
      cgButtonLinkList: [],
      title: "", //存表名
      EnhanceJS: "",
      cgButtonList: [],
      groupTag: [],
      queryInfo: [],
      code: "",
      // 表头
      columns: [],
      //列设置
      settingColumns: [],
      //列定义
      defColumns: [
        {
          title: "工单类型",
          align: "center",
          dataIndex: "processType",
          key: "processType",
          customRender: (text) => {
            if (text === 0) {
              return "标准工单";
            } else if (text === 1) {
              return "返修工单";
            } else if (text === 2) {
              return "拆零工单";
            } else if (text === 3) {
              return "改配工单";
            } else if (text === 4) {
              return "中试首样工单";
            } else if (text === 5) {
              return "非常规工单";
            } else if (text === 6) {
              return "中试小批量工单";
            } else if (text === 7) {
              return "工序外协工单";
            } else if (text === 8) {
              return "维修工单";
            } else if (text === 9) {
              return "科研加工工单";
            } else {
              return false;
            }
          },
        },
        {
          title: "任务来源",
          align: "center",
          dataIndex: "taskSource",
          key: "taskSource",
        },
        {
          title: "生产工单",
          align: "center",
          dataIndex: "productionno",
          key: "productionno",
        },
        {
          title: "工序工单",
          align: "center",
          dataIndex: "processbillno",
          key: "processbillno",
        },
        {
          title: "二级工序",
          align: "center",
          dataIndex: "processTwoname",
          key: "processTwoname",
        },
        {
          title: "线体",
          align: "center",
          dataIndex: "lineno",
          key: "lineno",
        },
        {
          title: "产品编码",
          align: "center",
          dataIndex: "productcode",
          key: "productcode",
        },
        {
          title: "产品名称",
          align: "center",
          dataIndex: "productname",
          key: "productname",
        },
        {
          title: "计划数量",
          align: "center",
          dataIndex: "planQty",
          key: "planQty",
        },
        {
          title: "工单状态",
          align: "center",
          dataIndex: "billnoStatus",
          key: "billnoStatus",
          customRender: (text) => {
            if (text === -1) {
              return "已删除";
            } else if (text === 0) {
              return "未发布";
            } else if (text === 1) {
              return "已发布";
            } else if (text === 2) {
              return "已开工";
            } else if (text === 3) {
              return "已暂停";
            }
          },
        },
        {
          title: "物料齐套状态",
          align: "center",
          dataIndex: "qistate",
          key: "qistate",
          customRender: (text) => {
            if (text === 0) {
              return "未齐套";
            } else if (text === 1) {
              return "齐套";
            } else if (text === 2) {
              return "外协已确认";
            } else {
              return false;
            }
          },
        },
        {
          title: "计划开始时间",
          dataIndex: "starttime",
          key: "starttime",
          align: "center",
          customRender: (text) => {
            return moment(text).format("YYYY-MM-DD");
          },
        },
        {
          title: "计划完成时间",
          dataIndex: "completiontime",
          key: "completiontime",
          align: "center",
          customRender: (text) => {
            return moment(text).format("YYYY-MM-DD");
          },
        },
        {
          title: "完成进度",
          dataIndex: "schedule",
          key: "schedule",
          align: "center",
          scopedSlots: {
            customRender: "schedule",
          },
        },
        {
          title: "操作",
          dataIndex: "action",
          align: "center",
          // scopedSlots: { customRender: "action" },
        },
      ],
      url: {
        list: "/mes-manufacture/mfProcess/out/list",
        delete: "/mes-code/mesBcProcessLabel",
        deleteBatch: "/mes-code/mesBcProcessLabel",
        exportXlsUrl: "/mes-code/mesBcProcessLabel/export",
        getColumns: "/mes-code/online/cgform/api/getColumns/",
        buttonAction: "/mes-code/online/cgform/api/doButton",
        // 齐套确认
        setOfConfirmationButton: "/mes-manufacture/mfProcess/out/confirm",
        // 外协编辑
        OutChange: "/mes-manufacture/mfProcess/out",
      },
      dictOptions: {},
    };
  },
  computed: {
    importExcelUrl: function () {
      return `${api.test}${this.url.importExcelUrl}`;
    },
    getWidth: function () {
      if (this.defColumns.length > 14) {
        return { width: "500px" };
      }
    },
    tableScroll: function () {
      if (this.columns.length > 13) {
        return { x: this.columns.length * 150 - 450 };
      }
    },
  },
  created() {
    this.initColumns();
  },

  methods: {
    initColumns() {
      //权限过滤（列权限控制时打开，修改第二个参数为授权码前缀）
      //this.defColumns = colAuthFilter(this.defColumns,'testdemo:');

      var key = this.$route.name + ":colsettings";
      let colSettings = Vue.ls.get(key);
      if (colSettings == null || colSettings == undefined) {
        let allSettingColumns = [];
        this.defColumns.forEach(function (item, i, array) {
          allSettingColumns.push(item.dataIndex);
        });
        this.settingColumns = allSettingColumns;
        this.columns = this.defColumns;
      } else {
        this.settingColumns = colSettings;
        const cols = this.defColumns.filter((item) => {
          if (item.key == "rowIndex" || item.dataIndex == "action") {
            return true;
          }
          if (colSettings.includes(item.dataIndex)) {
            return true;
          }
          return false;
        });
        this.columns = cols;
      }
    },
    //列设置更改事件
    onColSettingsChange(checkedValues) {
      var key = this.$route.name + ":colsettings";
      Vue.ls.set(key, checkedValues, 7 * 24 * 60 * 60 * 1000);
      this.settingColumns = checkedValues;
      const cols = this.defColumns.filter((item) => {
        if (item.key == "rowIndex" || item.dataIndex == "action") {
          return true;
        }
        if (this.settingColumns.includes(item.dataIndex)) {
          return true;
        }
        return false;
      });
      this.columns = cols;
    },

    //高级查询方法
    handleSuperQuery(arg) {
      if (!arg) {
        this.superQueryParams = "";
        this.superQueryFlag = false;
      } else {
        this.superQueryFlag = true;
        this.superQueryParams = JSON.stringify(arg);
      }
      this.loadData();
    },

    initDictConfig() {},

    // 弹出窗组件
    showDemoModal() {
      this.$refs.modalCompon.modalShow();
    },
    // 点击btn获取数据
    btnGetData(tableName, title) {
      getAction(`${this.url.getColumns}`, {
        tableName: tableName,
      }).then((res) => {
        if (res.code == 0) {
          this.queryInfo = res.data.columns;
          this.title = title;
          this.dictOptions = res.data.dictOptions;
          this.showDemoModal();
        } else {
          this.$message.warning(res.msg);
        }
      });
    },

    //筛选分组
    getGroupTag(arrList) {
      let arr = [];
      var map = {},
        dest = [];
      arrList.forEach((item, index) => {
        if (item.groupTag) {
          arr.push(item);
        }
      });
      for (var i = 0; i < arr.length; i++) {
        var ai = arr[i];
        if (!map[ai.groupTag]) {
          dest.push({
            groupTag: ai.groupTag,
            name: ai.groupName,
            data: [ai],
          });
          map[ai.groupTag] = ai;
        } else {
          for (var j = 0; j < dest.length; j++) {
            var dj = dest[j];
            if (dj.groupTag == ai.groupTag) {
              dj.data.push(ai);
              break;
            }
          }
        }
      }
      this.groupTag = dest;
      console.log(dest);
    },
    showLinkButton(item, record) {
      let btn = new ButtonExpHandler(item.exp, record);
      return btn.show;
    },

    initCgEnhanceJs(enhanceJs) {
      //console.log("--onlineList-js增强",enhanceJs)
      if (enhanceJs) {
        let Obj = eval("(" + enhanceJs + ")");
        this.EnhanceJS = new Obj(getAction, postAction, deleteAction);
        this.cgButtonJsHandler("created");
      } else {
        this.EnhanceJS = "";
      }
    },
    initCgButtonList(btnList) {
      let linkArr = [];
      let buttonArr = [];
      if (btnList && btnList.length > 0) {
        for (let i = 0; i < btnList.length; i++) {
          let temp = btnList[i];
          if (temp.buttonStyle == "button") {
            buttonArr.push(temp);
          } else if (temp.buttonStyle == "link") {
            linkArr.push(temp);
          }
        }
      }
      this.cgButtonLinkList = [...linkArr];
      this.cgButtonList = [...buttonArr];
      console.log("链接增强", this.cgButtonLinkList);
    },
    cgButtonJsHandler(buttonCode) {
      if (this.EnhanceJS[buttonCode]) {
        this.EnhanceJS[buttonCode](this);
      }
    },

    onClearSelected() {
      this.selectedRowKeys = [];
      this.selectionRows = [];
      this.selectedMainId = "";
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedMainId = selectedRowKeys[0];
      this.selectedRowKeys = selectedRowKeys;
      this.selectionRows = selectionRows;
    },
    handleDelete: function (id) {
      if (!this.url.delete) {
        this.$message.error("请设置url.delete属性!");
        return;
      }
      var that = this;
      deleteAction(that.url.delete + `/${id}`, {}).then((res) => {
        if (res.success) {
          that.$message.success(res.msg);
          that.loadData();
        } else {
          that.$message.warning(res.msg);
        }
      });
    },

    loadData(arg) {
      if (!this.url.list) {
        this.$message.error("请设置url.list属性!");
        return;
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1;
      }
      this.onClearSelected();
      var params = {
        pageNo: this.ipagination.current,
        limit: this.ipagination.pageSize,
        keyword: this.queryParam.ruleNo,
      };
      this.loading = true;
      getAction(this.url.list, params).then((res) => {
        if (res.success) {
          this.dataSource = res.data.records;
          this.ipagination.total = res.data.total;
        }
        if (res.code === 510) {
          this.$message.warning(res.msg);
        }
        this.loading = false;
      });
    },
    //齐套确认
    handleSetOfConfirmation() {
      putAction(this.url.setOfConfirmationButton, {
        ids: this.selectedRowKeys,
      }).then((res) => {
        if (res.success) {
          this.numberList = this.selectionRows;
          this.visible = false;
          this.numberVisible = true;
        }
        if (res.code === 510) {
          this.$message.warning(res.msg);
        }
        this.loading = false;
      });
    },
    //控制齐套确认对话框的显示与隐藏
    showModal() {
      // 显示弹窗判断是否选中一条数据
      if (this.selectedMainId) {
        this.visible = true;
      } else {
        this.$message.error("请选择一条数据！");
      }
    },
    handleOk(e) {
      this.handleSetOfConfirmation();
    },
    handleNotOk(e) {
      this.visible = false;
    },
    handleCancel() {
      this.numberVisible = true;
    },
    handleList() {
      if (this.childData.length > 0) {
        let arr = [];
          this.childData.forEach((item) => {
            this.isexistence(item, arr);
          });
          if (arr.indexOf(false) > 0) {
            this.$message.error("请输入数量");
          }else{
              putAction(this.url.OutChange, { elements: this.childData }).then(
            (res) => {
              if (res.code == 0) {
                this.$message.success("产出数量编辑成功！");
              } else {
                this.$message.error("产出数量编辑失败！");
              }
            }
          );
          this.numberVisible = false;
          this.loadData()
          }
      } else {
        this.$message.error("请输入数量");
      }
    },
    isexistence(data, obj) {
      if (data.qualifiedNum && data.productNum) {
        obj.push(true);
      } else {
        obj.push(false);
      }
    },
    handleCancel() {
      this.numberVisible = false;
    },
    geiChildData(data) {
      this.childData = data;
    },
  },
};
</script>
<style scoped>
@import "~@assets/less/common.less";
</style>